<template>
  <div class="flex flex-col h-full">
    <ReadCard
      ref="readCardRef"
      business-type="门诊退号"
      :call-back-data="formState"
      @read="onReadCardSuccess"
      @tab-change="onTabRadioChange"
      @change="onChangeCard"
    >
      <template #selfCost>
        <!-- <a-card :body-style="{ padding: '8px 12px' }"> -->
        <a-form ref="formRef" :model="formState" class="flex justify-between">
          <div class="flex">
            <a-form-item name="brName" class="w-[260px] mr-3 !mb-0">
              <SelectTable
                v-model:value="formState.brName"
                :search-params="{ stdate: formState.dateRange?.[0], eddate: formState.dateRange?.[1], miFlag: 0, ghzt: 0, cxtype: 'zf', type: 3 }"
                type="门诊挂号患者列表"
                placeholder="姓名/助记码/卡号/手机号/身份证号"
                @select="onSelect"
              />
            </a-form-item>
          </div>
          <div>
            <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
            <a-button type="primary" @click="chargeDetailList">刷新</a-button>
          </div>
        </a-form>
        <!-- </a-card> -->
      </template>
      <template #rightBtn>
        <div class="flex items-center">
          <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
          <a-button type="primary" @click="chargeDetailList">刷新</a-button>
        </div>
      </template>
    </ReadCard>
    <PatientInfoHeader :patient-info="patientInfo" :show-insurance="true" class="mt-2" @change="onClickReset">
      <div>
        <div class="flex items-center">
          <div class="ml-8"><PhoneOutlined class="mr-1" />{{ patientInfo.brMob || '-' }}</div>
          <div class="ml-8"><EnvironmentOutlined class="mr-1" />{{ patientInfo.brJtdz || '-' }}</div>
          <div class="ml-8"><IdcardOutlined class="mr-1" />{{ patientInfo.brSfz || '-' }}</div>
        </div>
      </div>
    </PatientInfoHeader>
    <div class="list-wrap mt-2 overflow-y-scroll relative" :style="{ height: getTableHeight() }">
      <BaseTitle title="挂号记录" class="mt-4" />
      <div v-for="(item, index1) in tableDataDetail" :key="index1" class="list w-full h-24 flex justify-between py-2 items-center mb-2">
        <div class="list-top ml-4 flex h-full items-center">
          <div class="w-72">
            <div class="w-full mt-2">
              <a-button v-if="item.ghzt === 0" class="list-top-status-ing">候诊中</a-button>
              <a-button v-if="item.ghzt === 1" class="list-top-status-end">已就诊</a-button>
              <a-button v-if="item.ghzt === 2" class="list-top-status-end">已退号</a-button>
              <a-button v-if="item.ghzt === 3" class="list-top-status-end">待回诊</a-button>
              <span class="list-top-time ml-4">{{ item.ghsj }}</span>
            </div>
            <div class="w-full mt-4">
              <span>{{ item.ghlb }}</span>
              <span class="font-bold ml-4 text-base">{{ item.ksmc }}</span>
              <span class="font-bold ml-2 text-base">{{ item.empName }}</span>
            </div>
          </div>
          <a-divider type="vertical" :style="{ height: '90%', margin: '0 10px' }" />
          <div>
            <div class="mt-2">
              <LabelValue label="门诊号" :value="item.jzbh" :width="400" label-class="w-[100px] text-right" />
            </div>
            <div v-if="!isArmy" class="flex mt-4">
              <LabelValue label="收费标准" :value="item.chargeStandardName" :width="240" label-class="w-[100px] text-right" />
              <LabelValue label="挂号费用" :value="formatMoney(item.zfy)" :width="220" label-class="w-[100px] text-right" />
              <LabelValue label="医保支付" :value="formatMoney(item.ybje)" :width="220" label-class="w-[100px] text-right" />
              <LabelValue label="个人支付" :value="formatMoney(item.zfje)" :width="220" label-class="w-[100px] text-right" />
              <LabelValue label="收据号" :value="item.pjhm" :width="220" label-class="w-[100px] text-right" />
            </div>
          </div>
        </div>
        <div class="w-1/6 text-right mr-4">
          <a-button type="primary" :disabled="item.ghzt !== 0" @click="refundRegistration(item)">退号</a-button>
        </div>
      </div>
      <a-empty v-if="tableDataDetail.length === 0 && !loading" />
      <a-spin v-if="loading" :spinning="loading" class="w-full h-full flex-center absolute top-0 left-0" />
    </div>
    <Refund
      v-model:open="priceOpen"
      :register-price="cancelInfo.sjdj"
      :vip-price="patientInfo.vipzf"
      :type="changeType"
      :business-data="{ ...cancelInfo }"
      :charge-title="chargeTitle"
      :loading-state="loadingState"
      @success="onSuccessPrice"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, createVNode } from 'vue'
import dayjs from 'dayjs'
import { PhoneOutlined, EnvironmentOutlined, IdcardOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import BaseTitle from '@/components/BaseTitle'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import PatientInfoHeader from '../components/PatientInfoHeader'
import Refund from '../components/RefundModal.vue'

const tableDataDetail = ref([])
const formState = ref({
  brName: '',
  ck: '',
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  kh: '',
  medType: '',
  bigIll: false,
  bigIllNum: undefined,
  indInjury: true,
  indInjuryNum: ''
})
const rowValue = ref({})
const priceOpen = ref(false)
const changeType = ref('zf') //zf 自费退号  yb 医保退号
const chargeTitle = ref('')
const patientInfo = ref({})
const cancelInfo = ref({})
const keycode = ref('')
const formRef = ref(null)
const loading = ref(false)
const loadingState = ref(false)
const isMedical = ref(false)
const tabActiveKey = ref('自费') //选中的
const readCardInfo = ref({})
const readCardRef = ref(null)
const onTabRadioChange = async (val) => {
  tabActiveKey.value = val
  onClickReset()
}
const onChangeCard = (info) => {
  readCardInfo.value = { ...readCardInfo.value, ...info }
}
const onClickReset = () => {
  formState.value = {
    brName: '',
    brId: '',
    dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  }
  formRef.value?.resetFields()
  patientInfo.value = {}
  cancelInfo.value = {}
  keycode.value = ''
  tableDataDetail.value = []
  readCardRef.value?.reset()
}
const onSelect = async (select) => {
  patientInfo.value = select
  formState.value.brName = select.brName
  chargeDetailList(0, 'zf')
}

const onReadCardSuccess = async (info) => {
  readCardInfo.value.kh = info.ybkResonse?.kh
  readCardInfo.value = { ...info, ck: readCardInfo.value.ck, mdtrtCertNo: info.mdtrtCertNo, mdtrtCertType: info.mdtrtCertType } || {}
  const { code, data = {}, msg } = await get('/common/patient/getPatientInfo?br_id=' + info.ybkResonse?.br_id)
  if (code !== 0) return message.error(msg || '获取患者信息失败')
  patientInfo.value = data || {}
  patientInfo.value.isOwnExpense = true
  formState.value = {
    dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
    ...readCardInfo.value.baseinfo,
    ck: formState.value.ck,
    kh: readCardInfo.value.ybkResonse?.kh
  }
  chargeDetailList(readCardInfo.value.isgb ? 2 : 1, 'yb')
}
const onSuccessPrice = async (params) => {
  loadingState.value = true
  //自费
  if (tabActiveKey.value === '自费') {
    const { code, msg } = await post('/outp/oupCharge/doOutPRefund', {
      pjhm: cancelInfo.value.pjhm,
      yylsh: cancelInfo.value.yylsh,
      ...params,
      tflx: cancelInfo.value.tflx,
      lshs: cancelInfo.value.dtlsh,
      type: '1'
    })
    loadingState.value = false
    if (code !== 0) return message.error(msg)
    priceOpen.value = false
    message.success(msg || '退号成功')
    onClickReset()
  } else {
    // formState.value.insutype
    //阜阳医保才会调壳验证密码
    let verRes = ''
    if (getSystemConfig('NMI_REGION_CODE') === '022' && formState.value.insutype === '310' && tabActiveKey.value === '社保卡') {
      verRes = await window.openExe?.iVerifyPIN()
    }
    const res = await post('outp/mzdj/medicalInsuranceRefundNumber', {
      jzbh: rowValue.value.jzbh,
      fphm: cancelInfo.value.pjhm,
      kh: readCardInfo.value.kh,
      mdtrtCertNo: readCardInfo.value.mdtrtCertNo,
      mdtrtCertType: readCardInfo.value.mdtrtCertType,
      mmJson: verRes ? verRes : undefined,
      tftype: 'GH',
      type: '1'
    })
    loadingState.value = false
    if (res.code !== 0) return message.error(res.msg || '退号失败')
    if (readCardInfo.value.isgb) {
      const { code, msg } = await post('outp/oupCharge/doSaveNMlOutPRefund', {
        pjhm: cancelInfo.value.pjhm,
        yylsh: cancelInfo.value.yylsh,
        ...params,
        tflx: cancelInfo.value.tflx,
        lshs: cancelInfo.value.dtlsh,
        newpjhm: res.data.pjhm,
        type: '1'
      })
      if (code !== 0) return message.error(msg)
      priceOpen.value = false
      message.success(msg || '退号成功')
      onClickReset()
    } else {
      let result = window.openExe?.readGHQQ(res.data)
      if (!window.openExe) {
        result =
          '{"response":{"czybm":"0000","sysResv":"1234567887654321Ti8ri8rTT8ir8rTiriT8TTir8Trrii8r8Tirc0a8006e","recvTime":"0004089798fc01d6","bbh":"0001","msgid":"9999999870020211229000824890","fhxx":"","jyqd":"10","xxlxm":"SK01","jyyzm":"","xzqhdm":"310000","jysj":"2021-12-29 11:16:38","jgdm":"99999998700","xxfhm":"P001","zdsbsbm":"","czyxm":"系统管理员","xxnr":{"translsh":"2101010287593929","zfcash":"5","dffj":"0.00","curaccountamt":"0.00","curaccount":"0.00","tc":"0.00","tccash":"0.00","dffjhisaccount":"0.00","cardid":"N02423258","accountattr":"1000000000000000","tchisaccount":"0.00","hisaccount":"0.00","dffjcash":"0.00","cardtype":"1","hisaccountamt":"0.00","personname":"测试卡0800"}}}'
      }
      const res1 = await post('outp/mzdj/doCallbackAPi', {
        jsonStr: result,
        jzbh: rowValue.value.jzbh,
        pjhm: cancelInfo.value.pjhm
      })
      if (res1.code !== 0) return message.error(res1.msg || '退号失败')
      const { code, msg } = await post('outp/oupCharge/doSaveNMlOutPRefund', {
        pjhm: cancelInfo.value.pjhm,
        yylsh: cancelInfo.value.yylsh,
        ...params,
        tflx: cancelInfo.value.tflx,
        lshs: cancelInfo.value.dtlsh,
        newpjhm: res.data.pjhm,
        type: '1'
      })
      if (code !== 0) return message.error(msg)
      priceOpen.value = false
      message.success(msg || '退号成功')
      onClickReset()
    }
  }
}
const refundRegistration = async (row) => {
  Modal.confirm({
    title: '提示',
    okText: '确定',
    centered: true,
    maskClosable: true,
    width: 560,
    cancelText: '取消',
    icon: createVNode(ExclamationCircleOutlined, { style: 'color:red' }),
    content: createVNode('div', { style: 'margin:24px 0;font-size:15px' }, '确定退号？'),
    async onOk() {
      rowValue.value = JSON.parse(JSON.stringify(row))
      const { code, msg, data } = await post('/outp/mzdj/doCancel', { jzbh: row.jzbh, yybh: row.yybh, type: '1' })
      if (code !== 0) message.error(msg || '退号失败')
      if (data) {
        cancelInfo.value = data || {}
        if (data.sjdj) {
          if (tabActiveKey.value === '自费') {
            changeType.value = 'zf'
          } else {
            changeType.value = 'yb'
            chargeTitle.value = `原收费${formatMoney(row.zfy)}  |  医保支付${formatMoney(row.ybje)}  分币￥${row.fbyh}  原收费流水号 ${row.yblsh}`
          }
          priceOpen.value = true
        } else {
          onSuccessPrice()
        }
      } else {
        message.success(msg)
      }
    }
  })
}
const chargeDetailList = async (miFlag = 0, cxtype = 'zf') => {
  loading.value = true
  const { code, data, msg } = await post('/outp/mzdj/getOutpRecordInfoList', {
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    brId: patientInfo.value.brId,
    miFlag: miFlag, // 医保状态 0：自费 1：五期 2：国家医保
    cxtype: cxtype, //挂号退费检索 查询类别 自费:zf 医保:yb
    type: 3,
    checkCallNumberConfig: false
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  tableDataDetail.value = data
  if (data && data.length > 0) {
    formState.value.medTypeName = data[0]?.medTypeName
    formState.value.insutypeName = data[0]?.insutypeName
    formState.value.insutype = data[0]?.insutype
  }
}
const getTableHeight = () => {
  const topHeight = '380'
  return window.innerHeight - topHeight + (isMedical.value ? 20 : 75)
}
const formatMoney = (val) => {
  if (val) {
    return '￥' + formatAmount(val)
  } else {
    return '￥' + '0.00'
  }
}
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
onMounted(() => {
  isMedical.value = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
})
</script>
<style lang="less" scoped>
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
.w60 {
  width: 60px;
}
.list-wrap {
  .list {
    background: #fff;
    border-radius: 4px 4px 4px 4px;
    .list-top {
      .list-top-status-ing {
        height: auto !important;
        padding: 1px 6px !important;
        color: #fff;
        background-color: var(--primary-color);
        border: none;
      }
      .list-top-status-end {
        height: auto !important;
        padding: 1px 6px !important;
        color: #fff;
        background-color: rgb(250, 173, 20);
        border: none;
      }
      .list-top-time {
        color: #000;
      }
      .list-top-status-men {
      }
    }
  }
}
</style>
